package com.woniu.adapter;

import com.woniu.outlet.mysql.dao.DailyCodeValuationDao;
import com.woniu.outlet.mysql.po.DailyCodeValuationMySQL;
import com.woniu.outlet.mysql.po.DailyCodeValuationMySQLExample;
import com.woniu.outlet.redis.CodeOneRedisDao;
import com.woniu.outlet.redis.po.DailyCodeTOne;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import sun.rmi.runtime.Log;

import java.util.List;

/**
 * 每日code和对应净值适配层
 */
@Component
@Slf4j
public class DailyCodeValuationAdapter {

    @Autowired
    private DailyCodeValuationDao dao;

    @Autowired
    private CodeOneRedisDao redisDao;

    /**
     * @return 得到所有的code和对应的净值
     */
    public List<DailyCodeValuationMySQL> getAllCode() {
        return dao.selectByExample(null);
    }

    /**
     * 根据codeId更新净值和每日日期
     *
     * @param mySQL 传入的DailyCodeValuationMySQL类，要有codeId,todayValuation,pullDate
     */
    public void updateTodayValuationByCodeId(DailyCodeValuationMySQL mySQL) {
        DailyCodeValuationMySQLExample example = new DailyCodeValuationMySQLExample();
        DailyCodeValuationMySQLExample.Criteria criteria = example.createCriteria();
        criteria.andCodeIdEqualTo(mySQL.getCodeId());
        dao.updateByExampleSelective(mySQL, example);
    }

    /**
     * 保存code信息
     *
     * @param mySQL DailyCodeValuationMySQL
     */
    public void saveCode(DailyCodeValuationMySQL mySQL) {
        dao.insert(mySQL);
    }

    /**
     * 查找code存不存在
     *
     * @param codeId
     */
    public String findCode(String codeId) {
        try {
            DailyCodeTOne dailyCodeTOne = redisDao.findById(codeId).orElseThrow(NullPointerException::new);
            if (dailyCodeTOne.getCodeId().equals(codeId)) return "y";
        } catch (NullPointerException e) {
            log.debug("redis中没有该code代码,到数据库中查找");
        }
        DailyCodeValuationMySQLExample example = new DailyCodeValuationMySQLExample();
        DailyCodeValuationMySQLExample.Criteria criteria = example.createCriteria();
        criteria.andCodeIdEqualTo(codeId);
        List<DailyCodeValuationMySQL> cs = dao.selectByExample(example);
        if (cs.size() > 0) {
            for (DailyCodeValuationMySQL c : cs) {
                if (c.getCodeId().equals(codeId)) {
                    return "y";
                }
            }
        }
        return "n";
    }
}
